import React from "react";
import { getUuid } from "utils/comm";

const baseDuedate = {
  isTimeout: "false",
  isRequiredComment:'0',
  calendarType: "CALENDAR_DAY",
  day: 0,
  hour: 0,
  minute: 0,
  timeoutNotifier: {
    notifier: [],
    channel: [],
  },
  warningSetting: {},
};
const getBaseWarningSetting = (warningRegular) => ({
  isWarning: "false",
  calendarType: "CALENDAR_DAY",
  warningRegular,
});
const baseAlert = {
  warningCode: "",
  day: 0,
  hour: 0,
  minute: 0,
  warningNotifier: {
    notifier: [],
    channel: [],
  },
};

const prepareForSubmit = (users) => {
  let hasInitiator = false;
  users.forEach((user) => {
    if (!user.type) {
      user.type = 'USR';
    } else if (user.type === 'INIT') {
      hasInitiator = true;
    }
    user.code = user.userCode;
  });

  if (!hasInitiator) {
    users.push({ type: 'INIT' });
  }
  return users;
}

export default class BaseDuedateSetting extends React.Component {
  // 流程变量引用相关处理
  changeUsersVarRefs = (users, isAdded, prevVarRefs) => {
    const { changeModelVariableRef, codeRefModel } = this.props;
    const isReset = false;
    const codes = users.filter((u) => u.type === "VAR").map(({ code }) => code);
    return changeModelVariableRef(
      codes,
      codeRefModel,
      isAdded,
      isReset,
      prevVarRefs,
    );
  };

  changeAlertsVarRefs = (alerts, isAdded, varRefs) => {
    let prevVarRefs = varRefs || null;
    alerts.forEach((alert) => {
      const { warningNotifier: { notifier = [] } = {} } = alert;
      prevVarRefs = this.changeUsersVarRefs(notifier, isAdded, prevVarRefs);
    });
    return prevVarRefs;
  };

  // alert对应warningRegular中的item
  getChangeAlerts = (alert, idx, alerts, clearAll = false, varRefs) => {
    const isDelete = clearAll || !alert;
    let newAlerts = [...alerts];
    let removedAlerts;
    let prevVarRefs = varRefs || null;
    if (clearAll) {
      removedAlerts = alerts;
      newAlerts = [];
    } else if (isDelete) {
      removedAlerts = newAlerts.splice(idx, 1);
    } else {
      // replace
      removedAlerts = newAlerts.splice(idx, 1, alert);
      prevVarRefs = this.changeAlertsVarRefs([alert], true);
    }
    this.changeAlertsVarRefs(removedAlerts, false, prevVarRefs);
    return newAlerts;
  };

  updateAlertsProperties = (alerts, warningSetting) => {
    const { onValueUpdate, timeoutSetting } = this.props;
    const value = {
      ...timeoutSetting,
      warningSetting: {
        ...warningSetting,
        warningRegular: alerts,
      },
    };
    onValueUpdate("timeoutSetting", value);
  };

  onUserSelect = (
    alerts,
    warningSetting,

    // 版本1(已废弃): 选择通知人员，可以从流程变量中取，所以要更新变量引用
    // newUsers,
    // oldUsers,
    // noticeChannel,

    // 版本2(已废弃): 只需要配置标题和内容
    // title,
    // content,

    // 版本3: 选择通知人员，只能从组织树中获取，无需更新变量引用
    users,
  ) => {
    const { onValueUpdate, timeoutSetting } = this.props;
    if (this.edittingUserType === "timeoutSetting") {
      // 处理流程变量引用
      // this.changeUsersVarRefs(newUsers, true);
      // this.changeUsersVarRefs(oldUsers, false);

      const value = {
        ...timeoutSetting,

        // 版本1(已废弃)
        // timeoutNotifier: {
        // notifier: newUsers,
        // channel: noticeChannel,
        // },

        // 版本2(已废弃)
        // title,
        // content,

        // 版本3
        timeoutNotifier: {
          notifier: prepareForSubmit(users),
          channel: [],
        },
      };
      onValueUpdate("timeoutSetting", value);
    } else if (this.edittingUserType === "warningSetting") {
      const newAlert = {
        ...alerts[this.edittingIndex],

        // 版本1(已废弃)
        // warningNotifier: {
        // notifier: newUsers,
        // channel: noticeChannel,
        // },

        // 版本2(已废弃)
        // title,
        // content,

        // 版本3
        warningNotifier: {
          notifier: prepareForSubmit(users),
          channel: [],
        },
      };
      // getChangeAlerts已经处理了流程变量引用
      const newAlerts = this.getChangeAlerts(
        newAlert,
        this.edittingIndex,
        alerts,
      );
      const value = {
        ...timeoutSetting,
        warningSetting: {
          ...warningSetting,
          warningRegular: newAlerts,
        },
      };
      onValueUpdate("timeoutSetting", value);
    }
  };

  // 节点处理是否必须表达意见
  onReCommentChecked = (e) => {
    const { onValueUpdate } = this.props;
    const  {checked}  = e.target;
    // console.log(checked)
    // const newDuedata = {
    //   ...baseDuedate,
    //   isRequiredComment: String(checked),
    //   warningSetting: getBaseWarningSetting(
    //     this.getChangeAlerts(null, 0, alerts, true),
    //   ),
    // };
    onValueUpdate("isRequiredComment", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  // 退回必填意见
  onBackChecked = (e) => {

    const { onValueUpdate } = this.props;
    const  {checked}  = e.target;
    // console.log(checked)
    // const newDuedata = {
    //   ...baseDuedate,
    //   isRequiredComment: String(checked),
    //   warningSetting: getBaseWarningSetting(
    //     this.getChangeAlerts(null, 0, alerts, true),
    //   ),
    // };
    onValueUpdate("requiredRollbackComment", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  // 允许不表态
  onVoteChecked = (checked) => {
    const { onValueUpdate } = this.props;
    onValueUpdate("mustExpress", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  // 强制选人
  onForcePickChecked = (checked) => {
    const { onValueUpdate } = this.props;
    onValueUpdate("forcePick", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  // 再次流经该节点，自动获取上次设置的候选人
  onAutoGetLastCandidateChecked = (checked) => {
    const { onValueUpdate } = this.props;
    onValueUpdate("autoGetLastCandidate", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  // 是否选中候选人
  onChooseCandidateUser = (checked) => {
    const { onValueUpdate } = this.props;
    onValueUpdate("isChooseCandidateUser", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  // 退回时，是否需要再次进行候选人设置
  onCleanCandidateUserSetting = (checked) => {
    const { onValueUpdate } = this.props;
    onValueUpdate("isCleanCandidateUserSetting", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

   // 是否配置检查点
   onConfigCheckPoint = (checked) => {
    const { onValueUpdate } = this.props;
    onValueUpdate("isConfigCheckPoint", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  // 人工选择后续节点
  onManualSelectNextNode = (checked) => {
    const { onValueUpdate } = this.props;
    onValueUpdate("manualSelectNextNode", checked === true ? '1' : '0');
    this.setState({ alertCodes: [] });
  };

  onTimeoutChecked = (e, alerts) => {
    const { onValueUpdate } = this.props;
    const { checked } = e.target;
    const newDuedata = {
      ...baseDuedate,
      isTimeout: String(checked),
      warningSetting: getBaseWarningSetting(
        this.getChangeAlerts(null, 0, alerts, true),
      ),
    };
    onValueUpdate("timeoutSetting", newDuedata);
    this.setState({ alertCodes: [] });
  };


  onSelectTimeoutUser = (timeoutSetting) => {
    const { title = "", content = "" } = timeoutSetting;
    const s = { title, content };
    this.edittingUserType = "timeoutSetting";
    this.setState({
      ...s,
      userSelectorVisible: true, // eslint-disable-line
    });
  };

  onTimeRadioChange = (e) => {
    const { onValueUpdate, timeoutSetting } = this.props;
    const { value } = e.target;
    const newDuedata = { ...timeoutSetting, calendarType: value };
    onValueUpdate("timeoutSetting", newDuedata);
  };

  onTimeoutValueChange = (valueObj) => {
    const { onValueUpdate, timeoutSetting } = this.props;
    const newDuedata = { ...timeoutSetting, ...valueObj };
    onValueUpdate("timeoutSetting", newDuedata);
  };

  onWarningCheck = (e, alerts) => {
    const { onValueUpdate, timeoutSetting } = this.props;
    const {
      target: { checked },
    } = e;
    let value;
    if (checked) {
      value = {
        ...timeoutSetting,
        warningSetting: {
          ...getBaseWarningSetting([{ ...baseAlert, uuid: getUuid() }]),
          isWarning: "true",
        },
      };
    } else {
      value = {
        ...timeoutSetting,
        warningSetting: {
          ...getBaseWarningSetting(this.getChangeAlerts(null, 0, alerts, true)),
          isWarning: "false",
        },
      };
    }
    onValueUpdate("timeoutSetting", value);
  };

  onWarningRadioChange = (e, warningSetting) => {
    const { onValueUpdate, timeoutSetting } = this.props;
    const { value } = e.target;
    const setting = { ...warningSetting, calendarType: value };
    const v = { ...timeoutSetting, warningSetting: setting };
    onValueUpdate("timeoutSetting", v);
  };

  onAlertCodeChange = (value, idx, alert, warningSetting, alerts) => {
    const newAlert = { ...alert, warningCode: value };
    const newAlerts = this.getChangeAlerts(newAlert, idx, alerts);
    this.updateAlertsProperties(newAlerts, warningSetting);
    const { alertCodes: oldCodes } = this.state;
    oldCodes[idx] = "";
    const newCodes = [...oldCodes];
    this.setState({ alertCodes: newCodes });
  };

  onAlertValueChange = (valueObj, alert, idx, warningSetting, alerts) => {
    const newAlert = { ...alert, ...valueObj };
    const newAlerts = this.getChangeAlerts(newAlert, idx, alerts);
    this.updateAlertsProperties(newAlerts, warningSetting);
  };

  onSelectAlertUser = (alert, idx) => {
    const { title = "", content = "" } = alert;
    const s = { title, content };
    this.edittingUserType = "warningSetting";
    this.edittingIndex = idx;
    this.setState({
      ...s,
      userSelectorVisible: true, // eslint-disable-line
    });
  };

  onAddAlert = (idx, alerts, warningSetting) => {
    const newAlert = { ...baseAlert, uuid: getUuid() };
    const newAlerts = [...alerts];
    newAlerts.splice(idx + 1, 0, newAlert);
    this.updateAlertsProperties(newAlerts, warningSetting);
  };

  onRemoveAlert = (idx, alerts, warningSetting) => {
    const newAlerts = this.getChangeAlerts(null, idx, alerts);
    this.updateAlertsProperties(newAlerts, warningSetting);
  };
}
